﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Word;

namespace VBAConvertor.Parsers
{
    public class AppPrefixParser : ILineParser
    {
        private static readonly Regex _WordPattern =
            new Regex(
                @"((?<seperator>[^\w])|^)(?<word>[\w\$]+)\b",
                RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.Singleline);

        private static readonly Type _AppType = typeof (Application);

        private static readonly HashSet<string> _AppMembers;

        static AppPrefixParser()
        {
            _AppMembers = new HashSet<string>()
                {
                    "ActiveDocument",
                    "Selection",
                    "ActiveWindow",
                    "Application",
                    "CaptionLabels",
                    "Dialogs",
                    "Options"
                };
        }

        public string Parse(Stack<ParseStatus> statuses, string lineContent, LinesReader reader, out bool success, ref bool lineClosed)
        {
            success = _WordPattern.IsMatch(lineContent);
            if (!success) return lineContent;
            return _WordPattern.Replace(lineContent, match =>
                {
                    if (match.Success)
                    {
                        if (match.Groups["seperator"].Value != "." && _AppMembers.Contains(match.Groups["word"].Value))
                        {
                            return match.Groups["seperator"].Value + "app." + match.Groups["word"].Value;
                        }
                        return match.Value;
                    }
                    throw new Exception();
                });
        }
    }
}
